import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import Home from "../pages/home.vue";
import cookies from './cookies';
import {useStore} from './store';
import {menuList} from "./menu";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      redirect: '/dashboard',
      children: [
        {
          path: '/dashboard',
          meta: { title: '数据概览' },
          component: () => import('../pages/index/dashboard.vue')
        },
        {
          path: '/notfound',
          meta: { title: '页面无法找到' },
          component: () => import('../pages/index/notfound.vue')
        },
        {
          path: '/ding_talk',
          meta: { title: '钉钉配置' },
          component: () => import('../pages/index/ding_talk.vue')
        },
        {
          path: '/mysql',
          meta: {title: 'Mysql配置'},
          component: () => import('../pages/index/mysql.vue')
        },
      ]
    },
    {
      path: '/login',
      meta: { title: '登录' },
      component: () => import('../pages/login.vue')
    },
    {
      path: '/qr',
      meta: { title: '授权' },
      component: () => import('../pages/qr.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      redirect: '/notfound',
    }
  ]
});

const whiteList = ['/login', '/qr'] // 不用重定向的白名单
router.beforeEach(async (to, from, next) => {
  /* 路由发生变化修改页面title */
  if (cookies.getCookie('token')) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (useStore().hasRouters) {
        next()
      } else {
        const routers:any = await useStore().generateRoutes(menuList)
        routers.map((item: RouteRecordRaw) => {
          router.addRoute('home', item)
        })
        if (to.redirectedFrom && to.redirectedFrom.name !== 'home') {
          next(to.redirectedFrom.fullPath || to.redirectedFrom.path)
        } else {
          if(!to.redirectedFrom){
            next()
          }else{
            next({path:'/dashboard'})
          }
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录名单中直接跳转
      next()
    } else {
      // 在空闲页面中，没有访问权限的其他页面被重定向到登录页面。登录白名单，直接去
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.onError((error) => {
  console.warn(error)
  router.push({ path: '/notfound'})
})

export default router
